package com.itlong.cloud.miniprogram.service.impl;

import com.itlong.cloud.POJO.PO.AppUserInfoPO;
import com.itlong.cloud.POJO.PO.FeedbackInfoPO;
import com.itlong.cloud.POJO.PO.WeChatUserOpenIdInfoPO;
import com.itlong.cloud.POJO.PO.WelinkBindRelationPO;
import com.itlong.cloud.POJO.VO.app.AppUserCacheVO;
import com.itlong.cloud.POJO.VO.miniprogram.WelinkUserVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppRegisterDao;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.SystemTypeEnum;
import com.itlong.cloud.miniprogram.dao.IWelinkUserDao;
import com.itlong.cloud.miniprogram.service.IWelinkUserService;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.network.https.HttpsPost;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      welink用户业务处理接口实现类
 * </desc>
 *
 * @createDate 2020/03/19
 */
@Service
@RefreshScope
public class WelinkUserServiceImpl implements IWelinkUserService {
    @Value("${" + PlatformConstants.WELINK_APPID + "}")
    public String appid;
    @Value("${" + PlatformConstants.WELINK_SECRET + "}")
    public String secret;

    @Value("${" + PlatformConstants.MINI_PROGRAM_USER_TOKEN_KEY + "}")
    public String MINI_PROGRAM_USER_TOKEN_KEY;
    @Autowired
    RedisService redisService;

    @Autowired
    IWelinkUserDao iWelinkUserDao;

    @Autowired
    IAppRegisterDao iAppRegisterDao;

    /**
     * <desc>
     *      用户登录
     * </desc>
     *
     * @param code
     * @return
     * @author Jiaqi.X
     * @createDate 2020/03/19
     */
    @Override
    public WelinkUserVO login(String code) throws IOException {
        String resultStr = HttpsPost.welinkLogin(this.getAccessKey(),PlatformConstants.WELINK_USER_LOGIN_URL+"?code="+code);
        Map<String,Object> result = JsonUtil.toObject(resultStr,HashMap.class);
        String welinkUserId = result.get("userId").toString();
        WelinkUserVO vo = iWelinkUserDao.login(welinkUserId);
        if(vo == null){
            vo = new WelinkUserVO();
        }
        vo.setWelinkUserId(welinkUserId);
        if (StringUtils.isNotBlank(vo.getUserId()) && StringUtils.isNotBlank(vo.getProjectIds())) {
            //模拟小程序登录
            AppUserInfoPO userInfoPO = iAppRegisterDao.getUserByPhoneNo(vo.getPhoneNo());
            String miniToken = UserTokenUtil.tokenEncrypt(userInfoPO.getUserId(), MINI_PROGRAM_USER_TOKEN_KEY, SystemTypeEnum.MINI_PROGRAM.getType());
            AppUserCacheVO appUserCacheVO = new AppUserCacheVO();
            appUserCacheVO.setNickName(userInfoPO.getNickName());
            appUserCacheVO.setPhotoUrl(userInfoPO.getIcon());
            //将信息存入缓存中
            appUserCacheVO.setPhoneNo(vo.getPhoneNo());
            appUserCacheVO.setUserId(userInfoPO.getUserId());
            appUserCacheVO.setMiniToken(miniToken);
            redisService.set(RedisConstant.MINI_PROGRAM_LOGIN + appUserCacheVO.getUserId(), RedisConstant.APP_USER_TOKEN_TIME, appUserCacheVO);
            //设置token
            vo.setToken(miniToken);
            vo.setType(3);
        }  else if(StringUtils.isNotBlank(vo.getUserId()) && StringUtils.isBlank(vo.getProjectIds())){
            vo.setType(2);
        }else{
            vo.setType(1);
        }
        return vo;
    }

    /**
     * <desc>
     *      检测手机号是否已绑定welink
     * </desc>
     *
     * @param phoneNum
     * @return
     * @author Jiaqi.X
     * @createDate 2020/03/19
     */
    @Override
    public String checkBindPhone(String phoneNum) {
        return iWelinkUserDao.checkBindPhone(phoneNum);
    }

    /**
     * <desc>
     *      保存绑定关系
     * </desc>
     *
     * @param welinkBindRelationPO
     * @return
     * @author Jiaqi.X
     * @createDate 2020/03/19
     */
    @Override
    public String save(WelinkBindRelationPO welinkBindRelationPO) throws Exception {
        welinkBindRelationPO.setCreateTime(new Date());
        welinkBindRelationPO.setWelinkBindId(LogicIdUtil.bussinessId());
        welinkBindRelationPO.setStatus(DataStatusEnum.NORMAL.getType());
        if(welinkBindRelationPO.getType() == 1) {
            iWelinkUserDao.save(SqlUtil.durableData(welinkBindRelationPO, PlatformConstants.TABLE_SAVE));
        }else{
            iWelinkUserDao.updatePhone(welinkBindRelationPO.getPhone(),welinkBindRelationPO.getWelinkUserId());
        }
        AppUserInfoPO userInfoPO = iAppRegisterDao.getUserByPhoneNo(welinkBindRelationPO.getPhone());
        //如果为空则是该手机号在APP未注册过，则需将该手机号保存至app-user-info表中
        String userId = "";
        String token = "";
        if (userInfoPO == null) {
            userId = LogicIdUtil.userBusinessId();
            token = UserTokenUtil.tokenEncrypt(userId, MINI_PROGRAM_USER_TOKEN_KEY, SystemTypeEnum.MINI_PROGRAM.getType());
            AppUserInfoPO appUserInfoPO = new AppUserInfoPO();
            appUserInfoPO.setUserId(userId);
            appUserInfoPO.setMiniToken(token);
            appUserInfoPO.setPhoneNum(welinkBindRelationPO.getPhone());
            appUserInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
            appUserInfoPO.setCreateTime(new Date());
            appUserInfoPO.setUpdateTime(new Date());
            appUserInfoPO.setIsOnline(1);
            iAppRegisterDao.save(SqlUtil.durableData(appUserInfoPO, PlatformConstants.TABLE_SAVE));
        }
        return welinkBindRelationPO.getWelinkBindId();
    }


    /**
     * <desc>
     *      获取welink accessTokenKey
     * </desc>
     * @return
     */
    private String getAccessKey() throws IOException {
        String accessToken = redisService.get(RedisConstant.WELINK_ACCESS_TOKEN_KEY);
        if(StringUtils.isBlank(accessToken)){
            Map<String,Object> params = new HashMap<>();
            params.put("client_id",appid);
            params.put("client_secret",secret);
            String resultStr = HttpsPost.getWelinkAccessToken(PlatformConstants.WELINK_ACCESS_TOKEN_URL, JsonUtil.toJSON(params));
            Map<String,Object> result = JsonUtil.toObject(resultStr,HashMap.class);
            accessToken = result.get("access_token").toString();
            redisService.set(RedisConstant.WELINK_ACCESS_TOKEN_KEY,RedisConstant.WELINK_ACCESS_TOKEN_KEY_CACHE_TIME,accessToken);
        }
        return accessToken;
    }

    /**
     * <desc>
     *      意见反馈
     * </desc>
     *
     * @param feedbackInfoPO
     * @return
     * @author Jiaqi.X
     * @createDate 2020/03/20
     */
    @Override
    public void saveFeedBack(FeedbackInfoPO feedbackInfoPO) throws Exception {
        feedbackInfoPO.setStatus(DataStatusEnum.DELETE.getType());
        feedbackInfoPO.setCreateTime(new Date());
        iWelinkUserDao.save(SqlUtil.durableData(feedbackInfoPO,PlatformConstants.TABLE_SAVE));
    }

    /**
     * <desc>
     *      更新用户信息
     * </desc>
     *
     * @param appUserInfoPO
     * @return
     * @author Jiaqi.X
     * @createDate 2020/03/20
     */
    @Override
    public void updateUserInfo(AppUserInfoPO appUserInfoPO) throws Exception {
        appUserInfoPO.setUpdateTime(new Date());
        iWelinkUserDao.update(SqlUtil.durableData(appUserInfoPO, PlatformConstants.TABLE_UPDATE));
    }

    /**
     * <desc>
     *      获取用户详情
     * </desc>
     *
     * @param userId
     * @return
     * @author Jiaqi.X
     * @createDate 2020/01/23
     */
    @Override
    public WelinkUserVO getUserInfo(String userId) {
        return iWelinkUserDao.getUserInfo(userId);
    }


}